package com.wuzhen.wzzt.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wuzhen.wzzt.vo.TemplateData;
import com.wuzhen.wzzt.vo.WxMssVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPushService {

    private String appID = "wxeb6b46d7e7662f62";
    //wxff39e92644997dd0

    private String appSecret = "40e139196e380cc42f8f8f2d2bfba2a8";
    //768c9d53f4b1b0f5f34e93507d248323


    private String templateId = "Crs309pI3c2O13jVPm-NMj4bUgqA1gD9ADcTzkN7c3c";

    public String push(String openid, Map<String, TemplateData> m) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTemplate_id(templateId);//订阅消息模板id
        wxMssVo.setPage("/pages/detail/index?id=148");

//        Map<String, TemplateData> m = new HashMap<>(5);
//        m.put("name1", new TemplateData("reedfan"));
//        m.put("thing2", new TemplateData("十分钟后"));
//        m.put("time3", new TemplateData("2022:06:18"));
//        m.put("thing4", new TemplateData("浙江省杭州市"));
//        m.put("thing5", new TemplateData("记得戴口罩"));

        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        System.out.println(responseEntity);
        return responseEntity.getBody();
    }

    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", appID);  //
        params.put("APPSECRET", appSecret);  //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        return Access_Token;
    }

}
